package handlers

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"rbac/cache"
	"rbac/models"
	"rbac/pkg"
	"strconv"
	"time"
)

func UserLogin(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "字段不能为空",
		})
		return
	}
	login_key := "login_key" + username
	errcount, _ := cache.Rdb.Get(cache.Ctx, login_key).Int()
	if errcount >= 3 {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "密码错误3次",
		})
		return
	}
	var user models.User
	models.DB.Where("username = ?", username).First(&user)
	if user.ID == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "用户名不存在",
		})
		return
	}
	if user.Password != pkg.Md5Str(password) {
		cache.Rdb.Incr(cache.Ctx, login_key)
		if errcount >= 2 {
			cache.Rdb.Set(cache.Ctx, login_key, 3, time.Hour*2)
			c.JSON(http.StatusOK, gin.H{
				"code": 0,
				"msg":  "密码错误3次,封禁2小时",
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
}
func RoleAddNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	data := models.RoleNode{
		Model: gorm.Model{},
		Rid:   rid,
		Nid:   nid,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "权限分配失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "权限分配成功",
		"data": data,
	})
	return
}
func UserRole(c *gin.Context) {
	uid, _ := strconv.Atoi(c.Query("uid"))
	var role []models.Role
	//SELECT
	//*
	//	FROM
	//roles
	//LEFT JOIN user_roles ON user_roles.rid = roles.id
	//WHERE
	//user_roles.uid = 1
	models.DB.Table("roles").Joins("left join user_roles on user_roles.rid=roles.id").Where("user_roles.uid=?", uid).Find(&role)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "success",
		"data": role,
	})
}
func RoleNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.Query("rid"))
	var node []models.Node
	models.DB.Table("nodes").Joins("left join role_nodes on role_nodes.nid=nodes.id").Where("role_nodes.rid=?", rid).Find(&node)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "success",
		"data": node,
	})
}
